<script setup name="printConfig">
import {
  GetDailtAPI,
  GetListAPI,
  DelDataAPI,
  AddDataAPI,
  EditDataAPI,
  UpdateDefaultValueAPI,
} from '@/api/system/printConfig'

import Print from './print.vue'

import addForm from './addForm.vue'

import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()

// 封装 方法 字典查询
const { sys_print_type } = proxy.useDict('sys_print_type')

const router = useRouter()

const formRef = ref(null)

const tableData = ref([])

const ruleForm = ref({})

// 查询条件
const selectList = ref([
  //   { type: '日期范围' },
  // {
  //   label: '模板类型',
  //   model: 'printType',
  //   type: '下拉单选',
  //   opt: sys_print_type,
  // },
  { label: '模板名称', model: 'printName', type: '输入框' },
])

// 列表枚举
const column = ref([
  { label: '模板名称', prop: 'printName' },
  { label: '打印单据', prop: 'printCorrelationName' },
  { label: '是否默认', prop: 'sw' },
  { label: '操作', prop: 'x', width: '250' },
])

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10,
})

// 状态
const state = reactive({
  rows: [], // 勾选数据
  ids: [], // 勾选id
  title: '', // 弹窗标题
  delDisabled: false, // 禁用 多选
  examineDisabled: false, // 禁用 单选
  isShow: false, // 新增 修改弹窗
  configIsShow: false, // 配置弹窗
})

// 勾选列表数据时
const handleSelectionChange = (selection) => {
  state.rows = selection
  state.ids = selection.map((item) => item.printId)
  state.delDisabled = !selection.length
  selection.length <= 0 || selection.length > 1
    ? (state.examineDisabled = true)
    : (state.examineDisabled = false)
}
handleSelectionChange([])

// 新增 弹窗
const add = () => {
  state.title = '新增'
  state.isShow = true
}

// 修改 弹窗
const edit = async (id) => {
  try {
    proxy.loading('请稍候...')
    state.title = '修改'
    const { data: res } = await GetDailtAPI(id)
    ruleForm.value = res
    state.isShow = true
  } catch {
  } finally {
    proxy.closeLoading()
  }
}

// 配置 弹窗
const config = async (val) => {}

// 查看 弹窗
const dxamine = async (id) => {
  try {
    proxy.loading('请稍候...')
    state.title = '查看'
    const { data: res } = await GetDailtAPI(id)
    ruleForm.value = res
    state.isShow = true
  } catch {
  } finally {
    proxy.closeLoading()
  }
}

// 新增提交后台
const addSub = async () => {
  const res = await formRef.value.submit()
  if (!res) return
  try {
    state.btnLoading = true
    await AddDataAPI(res)
    getList()
    close()
    proxy.successMsg('新增成功')
  } catch {
  } finally {
    state.btnLoading = false
  }
}

// 修改提交后台
const editSub = async () => {
  const res = await formRef.value.submit()
  if (!res) return
  try {
    state.btnLoading = true
    await EditDataAPI(res)
    getList()
    close()
    proxy.successMsg('修改成功')
  } catch {
  } finally {
    state.btnLoading = false
  }
}

// 配置修改保存
const configEdit = async (val) => {
  proxy.loading('请稍候...')
  try {
    await EditDataAPI({
      printId: ruleForm.value.id,
      printCompile: val,
    })
    getList()
    close()
    proxy.successMsg('配置成功')
  } catch {
  } finally {
    proxy.closeLoading()
  }
}

// 删除
const remove = async (val) => {
  const MesBox = await proxy.DelMessageBox()
  if (!MesBox) return
  await DelDataAPI(val ? val : state.ids.join(','))
  getList()
  close()
  proxy.successMsg('删除成功')
}

// 修改默认
const switchChange = async (val) => {
  const result = await proxy.MessageBox(
    ` ${
      val.defaultValue == '1' ? '是否确认开启默认状态' : '是否将默认状态关闭'
    }?`
  )
  if (!result) {
    val.defaultValue = val.defaultValue == '1' ? '0' : '1'
    return
  }
  try {
    await UpdateDefaultValueAPI({
      printId: val.printId,
      defaultValue: val.defaultValue,
    })
    getList()
    proxy.successMsg('修改成功!')
  } catch {
    val.defaultValue = val.defaultValue == '1' ? '0' : '1'
  }
}

const close = () => {
  state.isShow = false
  state.configIsShow = false
  ruleForm.value = {}
}

// 条件查询
const selectSubmit = (Obj) => {
  for (let KEY in Obj) {
    query[KEY] = Obj[KEY]
  }
  getList()
}

// 获取列表
const getList = async () => {
  state.loading = true
  try {
    const res = await GetListAPI(query)
    tableData.value = res.rows
    state.total = res.total
  } catch (error) {
  } finally {
    state.loading = false
  }
}
getList()
sessionStorage.setItem('print', 1)
</script>
<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-selectForm :selectForm="selectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <div></div>
      <p-table
        :isSel="false"
        :loading="state.loading"
        :column="column"
        :data="tableData"
        :total="state.total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @change="handleSelectionChange"
        @pagination="getList"
      >
        <template #buttons>
          <el-button
            type="primary"
            v-hasPermi="['system:printTemplate:add']"
            @click="add"
            >新增</el-button
          >
          <el-button
            type="primary"
            v-hasPermi="['system:printTemplate:config']"
            @click="router.push(`/system/print-template-config`)"
            >配置</el-button
          >

          <el-button
            type="danger"
            :disabled="state.delDisabled"
            v-hasPermi="['system:printTemplate:remove']"
            @click="remove(false)"
            >删除</el-button
          ></template
        >
        <template #columnCell="{ column, record }">
          <p-switch
            @change="switchChange(record)"
            v-if="column.prop == 'sw'"
            v-model="record.defaultValue"
          />
          <div v-if="column.prop == 'x'">
            <router-link
              :to="`/system/print-template-config?printPageId=${record.printCorrelation}`"
            >
              <el-link
                type="primary"
                text="字段配置"
                v-hasPermi="['system:printTemplate:textConfig']"
              >
              </el-link>
            </router-link>
            <el-link
              type="primary"
              text="配置内容"
              v-hasPermi="['system:printTemplate:configConent']"
              @click="
                router.push(
                  `/system/print-template-data?id=${record.printId}&printCorrelation=${record.printCorrelation}`
                )
              "
            />
            <el-link
              type="primary"
              text="查看"
              v-hasPermi="['system:printTemplate:query']"
              @click="dxamine(record.printId)"
            />
            <el-link
              type="primary"
              text="修改"
              v-hasPermi="['system:printTemplate:edit']"
              @click="edit(record.printId)"
            />
            <el-link
              type="primary"
              text="删除"
              v-hasPermi="['system:printTemplate:remove']"
              @click="remove(record.printId)"
            />
          </div>
        </template>
      </p-table>
    </el-card>
    <!-- 新增 修改 查看 -->
    <p-dialog
      v-model="state.isShow"
      :title="state.title"
      @ok="state.title == '新增' ? addSub() : editSub()"
      @close="close"
      width="60%"
    >
      <addForm
        ref="formRef"
        :title="state.title"
        :data="ruleForm"
        :disabled="state.title == '查看'"
      />
    </p-dialog>
    <p-dialog
      v-model="state.configIsShow"
      title="配置-(Ctrl+Z可撤回上一步哦)"
      @close="close"
      width="90%"
    >
      <template #body>
        <Print
          @exportJson="configEdit"
          :template-data="ruleForm.tableData"
          :elementData="ruleForm.elementList"
        />
      </template>
    </p-dialog>
  </div>
</template>
<style lang="scss" scoped></style>
